import React from 'react';
import PropTypes from 'prop-types';
import { Field, reduxForm } from 'redux-form';
import { FormattedMessage, injectIntl } from 'react-intl';
import {
    TextArea,
    TextField,
    Select,
    Button,
    Col,
    Row
  } from '@folio/stripes/components';

  function asyncValidate(values, dispatch, props, blurredField) {
    const { httpValidatorInvoke, initialValues } = props;
  
    if (values[blurredField]) {
      values[blurredField] = values[blurredField].trim();
    }
  
    const curValue = values[blurredField];
  
    if (!!initialValues && initialValues.id) {
      const prevValue = initialValues[blurredField];
      if (curValue !== prevValue) {
        return asyncValidateField(blurredField, curValue, httpValidatorInvoke);
      } else {
        return new Promise((resolve, reject) => {
          return resolve();
        });
      }
    } else if (blurredField) {
      const promises = [];
  
      promises.push(
        asyncValidateField(
          blurredField,
          values[blurredField],
          httpValidatorInvoke
        )
      );
      return Promise.all(promises);
    } else {
      return Promise.all([]);
    }
  }
function asyncValidateField(field, value, validator) {
  return new Promise((resolve, reject) => {
    const query = {};
    if (!value) {
      return resolve();
    }
    query[field] = value;
   
    validator.reset();
    return validator
      .GET({ params: { query: `(  year = ${query.year} and status == "1" ) ` } })
      .then(result => {
        if (result.totalRecords && result.totalRecords !== 0) {
          const error = {};
          error[field] =  <FormattedMessage id={"ui-party.other.already.exists"}/>;
          // <FormattedMessage id="ui-party.messageTemplate.data.name.error"/>
          return reject(error);
        } else {
          return resolve();
        }
      });
  });
}

function validate(values, props) {
    const errors = {};
  
    if (!values || !values.year) {
      
      errors.year =  <FormattedMessage id={"ui-party.errors.missingRequiredField"}/>;
    }
    if (!values || !values.late) {
      errors.late =  <FormattedMessage id={"ui-party.errors.missingRequiredField"}/>;
    }
    if (!values || !values.leave) {
      errors.leave =  <FormattedMessage id={"ui-party.errors.missingRequiredField"}/>;
    }
    if (!values || !values.absence) {
      errors.absence =  <FormattedMessage id={"ui-party.errors.missingRequiredField"}/>;
    }
    if (!values || !values.leaveEarly) {
      errors.leaveEarly =  <FormattedMessage id={"ui-party.errors.missingRequiredField"}/>;
    }
    if (!values || !values.prisonTermDay) {
      errors.prisonTermDay =  <FormattedMessage id={"ui-party.errors.missingRequiredField"}/>;
    }
    return errors;
  }
class editForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {};
    }
    static propTypes = {
        handleSubmit: PropTypes.func.isRequired,
        initialValues: PropTypes.object,
        dictionary: PropTypes.object,
        cleanSearch: PropTypes.func,
        intl: PropTypes.func,
        cancel:PropTypes.func,
        ascriptionNameList:PropTypes.array,
        exitFlag:PropTypes.bool
      };
    render() {
        const footer = (

            <div>
              <Button onClick={this.props.cancel}>
                <FormattedMessage id="ui-party.cancel" />
              </Button>  
               <Button buttonStyle="primary" marginBottom0 type="submit">
                <FormattedMessage id="ui-party.saveAndExit" />
              </Button>
            </div>
    
        );
        const { handleSubmit, intl } = this.props;
        return (
            <Row center="xs" style={{ width: '100%' }}>
        <Col xs={6}>
          <form data-test-form-page id="form-add" onSubmit={handleSubmit}>
          
            <Field
              component={TextField}
              name="year"
              label={
                <FormattedMessage id="ui-party.loans.columns.party.rules.year" />
              }
              hasClearIcon
              placeholder={'请填写年份,例如2020'}
              type="number"
              min="2020"
              max="2050"
              required
            />
            <Field
              component={TextField}
              name="late"
              label={
                <FormattedMessage id="ui-party.loans.columns.party.rules.late" />
              }
              hasClearIcon
              type="number"
              min="1"
              max="9999"
              required
            />
            <Field
              component={TextField}
              name="leave"
              label={
                <FormattedMessage id="ui-party.loans.columns.party.rules.leave" />
              }
              hasClearIcon
              type="number"
              min="1"
              max="9999"
              required
            />
                    <Field
              component={TextField}
              name="absence"
              label={
                <FormattedMessage id="ui-party.loans.columns.party.rules.absent" />
              }
              hasClearIcon
              type="number"
              min="1"
              max="9999"
              required
            />
                    <Field
              component={TextField}
              name="leaveEarly"
              label={
                <FormattedMessage id="ui-party.loans.columns.party.rules.leave.early" />
              }
              hasClearIcon
              type="number"
              min="1"
              max="9999"
              required
            />
                     <Field
              component={TextField}
              name="prisonTermDay"
              label={
                <FormattedMessage id="ui-party.loans.columns.party.rules.prisonTermDay" />
              }
              hasClearIcon
              type="number"
              min="1"
              max="365"
              required
            />

            {footer}
          </form>
        </Col>

      </Row>
        );
    }
}
 
export default injectIntl(
    reduxForm({
      form: 'rulesEditForm' + new Date().getTime(),
      validate,
      asyncValidate,
      asyncBlurFields: ['year'],
      navigationCheck: true,
      enableReinitialize: true
    })(editForm)
  );
